package com.itany.shop.dao.impl;

import com.itany.shop.dao.OrderDao;
import com.itany.shop.entity.Order;
import com.itany.shop.factory.ObjectFactory;
import com.itany.shop.util.JDBCTemplate;
import com.itany.shop.util.KeyHolder;
import com.itany.shop.util.PreparedStatementCreator;

import java.sql.Connection;
import java.sql.PreparedStatement;

/**
 * @Author:石小俊
 * @Date:2022/11/16 16:57
 * @Version:1.0-SNAPSHOT
 * @Description:
 */
public class OrderDaoImpl implements OrderDao {

    private JDBCTemplate jdbcTemplate = (JDBCTemplate) ObjectFactory.getObject("jdbc");

    @Override
    public Integer insertReturnPrimaryKey(Order order) {
        KeyHolder keyHolder = new KeyHolder();
        jdbcTemplate.update(new PreparedStatementCreator() {
            @Override
            public PreparedStatement createPreparedStatement(Connection conn) throws Exception {
                String sql = new StringBuffer()
                        .append(" insert into ")
                        .append(" t_order ")
                        .append("   (no,price,user_id)")
                        .append(" values ")
                        .append("   (?,?,?)")
                        .toString();
                PreparedStatement ps = conn.prepareStatement(sql,PreparedStatement.RETURN_GENERATED_KEYS);
                ps.setString(1,order.getNo());
                ps.setDouble(2,order.getPrice());
                ps.setInt(3,order.getUser().getId());
                return ps;
            }
        },keyHolder);
        return keyHolder.getKey();
    }
}
